<!-- employeeMgrPage.vue -->
<template>
  <div class="employee-mgr-container">
    <el-row>
      <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
        <el-form :inline="true" :model="filter" class="demo-form-inline">
          <el-form-item label="姓名">
            <el-input v-model="filter.name" placeholder="员工姓名" clearable />
          </el-form-item>

      

          <el-form-item label="状态">
            <el-select v-model="filter.enable" placeholder="全部" clearable>
              <el-option label="全部" value="" />
              <el-option label="启用" :value="true" />
              <el-option label="禁用" :value="false" />
            </el-select>
          </el-form-item>

          <el-form-item label="登录权限">
            <el-select v-model="filter.authorized" placeholder="全部" clearable>
              <el-option label="全部" value="" />
              <el-option label="有权限" :value="true" />
              <el-option label="无权限" :value="false" />
            </el-select>
          </el-form-item>

          <el-form-item style="width: 300px" label="入职日期">
            <el-date-picker 
              v-model="dateRange" 
              type="daterange" 
              range-separator="~"
              start-placeholder="开始日期" 
              end-placeholder="结束日期" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24" style="padding-top: 24px; padding-left: 24px;">
        <el-button icon="Plus" @click="createEmployee()" type="primary">新增员工</el-button>
        <el-button icon="Refresh" @click="refreshList">刷新列表</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24" style="padding:12px; min-height: 400px; height: 70vh;">
        <el-table 
          v-loading="loading" 
          :data="dataList" 
          style="width: 100%; min-width: 600px; height: 100%;"
          @row-click="handleRowClick">
          
          <el-table-column label="姓名" align="center" prop="name" />
                    
          <el-table-column label="手机号" align="center" prop="mobNumber" />
          
          <el-table-column label="职位" align="center" prop="title" />
          
          <el-table-column label="入职日期" align="center">
            <template #default="scope">
              {{ formatDate(scope.row.joinDate) }}
            </template>
          </el-table-column>
          
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.available ? 'success' : 'danger'">
                {{ scope.row.available ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="登录权限" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.loginAuthorized ? 'success' : 'info'">
                {{ scope.row.loginAuthorized ? '有权限' : '无权限' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-link :underline="false" type="primary" @click.stop="showDetail(scope.row)">
                详情
              </el-link>             
              <el-link 
                v-if="isDeleteAble(scope.row)" 
                :underline="false" 
                type="danger" 
                style="margin-left: 12px;"
                @click.stop="deleteEmployee(scope.row)">
                删除
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div style="width: 80%; min-width: 600px; margin: 0 auto; padding: 0;">
      <pagination 
        v-show="total > 0" 
        :total="total" 
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" 
        @pagination="getList" />
    </div>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { EnterpriseMgtUiAction } from '../../public/engine/uiAction/enterpriseMgtUiAction'
import { DataPage } from '../../public/network/communicationConverter'
import { EmployeeFilter } from '../../public/engine/enterpriseMgt/employeeFilter'
import { Engine } from '../../public/engine/engine'
import EventBus from '../../public/engine/ipc/eventBus'
import { deleteEmployeeDataNetworkCache } from '../../public/network/api'
import { DateUtil } from '../../public/utils/dateUtil'
import { uiNavigation } from '../../public/views/uiEntrance/uiNavigation'

export default {
  name: 'emplyees',

  data() {
    return {
      loading: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
      },
      filter: new EmployeeFilter(),
      dateRange: [],
      dataList: [],
      enterpriseMgtUiAction: new EnterpriseMgtUiAction(),
      Engine
    }
  },

  mounted() {
    this.getList()
    EventBus.on('employeeDataUpdated', this.getList)
  },

  beforeUnmount() {
    EventBus.off('employeeDataUpdated', this.getList)
  },

  methods: {
     isDeleteAble(employee) {
      // owner 成员不可删除
      return employee.id != Engine.profile.org.owner
    },
    async getList() {
      try {
        this.loading = true

        // Update filter with date range
        if (this.dateRange?.length === 2) {
          this.filter.joinStartDate = this.dateRange[0]
          this.filter.joinEndDate = new Date(this.dateRange[1])
          this.filter.joinEndDate.setHours(23, 59, 59, 999)
        } else {
          this.filter.joinStartDate = null
          this.filter.joinEndDate = null
        }

        const res = await this.enterpriseMgtUiAction.getEmployeeData({
          pageInfo: new DataPage(this.queryParams.pageNum, 0, this.queryParams.pageSize),
          filter: this.filter.toJson()
        })

        if (res?.data?.dataList) {
          this.dataList = res.data.dataList
          this.total = res.data.pageInfo?.total || res.data.dataList.length
        } else if (res?.resErr) {
          ElMessage.error('获取员工列表失败: ' + res.resErr)
        }
      } catch (error) {
        console.error('获取员工列表失败', error)
        ElMessage.error('获取员工列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetSearch() {
      this.filter = new EmployeeFilter()
      this.dateRange = []
      this.queryParams.pageNum = 1
      this.getList()
    },

    refreshList() {
      deleteEmployeeDataNetworkCache()
      this.getList()
    },

    createEmployee() {
      uiNavigation.showEmployeeDetailPage(this.$router)
    },

    showDetail(row) {
      uiNavigation.showEmployeeDetailPage(this.$router, { id: row.id })
    },

    editEmployee(row) {
      uiNavigation.showEmployeeDetailPage(this.$router, { id: row.id, mode: 'edit' })
    },

    handleRowClick(row) {
      this.showDetail(row)
    },

    async deleteEmployee(row) {
      try {
        await ElMessageBox.confirm(
          `确定要删除员工【${row.name}】吗?`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const res = await this.enterpriseMgtUiAction.deleteEmployeeData(row.id)

        if (res?.data != null) {
          ElMessage.success('删除成功')
          this.getList()
        } else if (res?.resErr) {
          ElMessage.error('删除失败: ' + res.resErr)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除操作失败')
        }
      }
    },

    formatDate(date) {
      if (!date) return ''
      return DateUtil.getDayTitle(date)
    }
  }
}
</script>

<style scoped>
.employee-mgr-container {
  padding-top: 0px;
  padding-left: 20px;
}
</style>